#!/bin/sh
# PCP QA Test No. 1344
# pmmgr monitor/err functionality
#
# Copyright (c) 2017 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

which pmmgr >/dev/null 2>&1 || _notrun "No pmmgr binary installed"
[ $PCP_PLATFORM = linux ] || _notrun "Test uses commands only on Linux"

_cleanup()
{
    $sudo rm -rf $tmp $tmp.*
}

_filter()
{
    sed -e 's,^\[.*\],TIMESTAMP,' \
        -e 's,pmmgr.[0-9]*/[0-9]*.,pmmgr(PID/TID),' \
        -e 's, /.*\.err,ERRORFILE,' \
        -e 's, sh.*/no,SH /no,' \
        -e 's,sure: .*,sure: ERROR,'  # strip "No such file or directory" type message
}

status=1	# failure is the default!
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15


# real QA test starts here
mkdir -p $tmp.config
echo "pmmgr plain startup" | tee -a $seq.full
echo 'local:' >$tmp.config/target-host
echo 'localhost' >>$tmp.config/target-host
echo 'pcp://localhost:44321/' >>$tmp.config/target-host
echo 'localhost6' >>$tmp.config/target-host
echo 'pcp://localhost6:44321/' >>$tmp.config/target-host
echo 0 > $tmp.config/target-threads

# configure the test proper
echo '/no/such/program/for/sure' > $tmp.config/monitor # something that'll cause a message to stderr
echo 'dummy' > $tmp.config/hostid-static
echo "$tmp.config" > $tmp.config/log-directory

pmmgr -v -v -p 1 -l $tmp.out -c $tmp.config >$tmp.valout 2>$tmp.valerr &
pid=$!
echo "pid=$pid" >>$seq.full

date >>$seq.full
echo "let pmmgr run /monitor a few times" | tee -a $seq.full
sleep 10 # expecting tenish -p poll iterations!

echo "look for err: messages" | tee -a $seq.full
# pick out the error notices only; only a few are needed
grep 'err:.*/no/such/program' $tmp.out | _filter | head -4

echo "kill pmmgr" | tee -a $seq.full
kill $pid
sleep 4
if kill -0 $pid >/dev/null 2>&1
then
    echo "pmmgr (pid=$pid) did not die, try harder ..." >>$seq.full
    kill -KILL $pid >/dev/null 2>&1
    if kill -0 $pid >/dev/null 2>&1
    then
	echo "pmmgr (pid=$pid) will not die!" >>$seq.full
    fi
fi
pid=

echo >>$seq.full
echo "collecting recent daemon logs:" >>$seq.full
for log in $tmp.out $tmp.config/*/*
do
    if [ -f "$log" ]
    then
	echo "-- $log --" >>$seq.full
	cat $log >>$seq.full
    fi
done
# success, all done
status=0
exit
